package cn.itsource.user.controller;

import cn.itsource.basic.exception.BusinessException;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.PageList;
import cn.itsource.user.domain.User;
import cn.itsource.user.dto.UserDto;
import cn.itsource.user.query.UserQuery;
import cn.itsource.user.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
@Api(tags = "用户接口",description = "用户接口详细描述")
public class UserController {
    @Autowired
    private IUserService userService;
    /**
     * 查询一个  localhost:8080/user/findone  1
     * localhost:8080/user/1
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "用户查找",notes = "根据ID查找用户")
    public User findOne(@PathVariable("id") Long id){
        User one = userService.findOne(id);
        return one;
    }

    /**
     * 查询所有localhost:8080/user
     * @return
     */
    @GetMapping
    @ApiOperation(value = "用户查找",notes = "查找所有用户")
    public List<User> findAll(){
        List<User> list = userService.findAll();
        return list;
    }
    @PutMapping  /*@RequestBody  接收请求体localhost:8080/user*/
    @ApiOperation(value = "添加或者修改用户",notes = "添加或者修改用户")
    public AjaxResult addorUpdate(@RequestBody User user){
        try {
            if (user.getId()==null){//添加
                userService.add(user);
            }else{//修改
                userService.update(user);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("操作失败");
        }
    }

    @DeleteMapping("/{id}")  /*@RequestBody  接收请求体localhost:8080/user/4*/
    @ApiOperation(value = "删除用户",notes = "根据ID删除用户")
    public AjaxResult delete(@PathVariable("id")Long id){
        try {
            userService.remove(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("操作失败");
        }
    }

    @PostMapping
    @ApiOperation(value = "分页查找用户",notes = "分页查找用户")/*localhost:8080/user*/
    public PageList<User> queryForPage(@RequestBody UserQuery userQuery){
        PageList<User> pageList = userService.queryForPage(userQuery);
        return pageList;
    }

    @PostMapping("/register/phone")
    public AjaxResult phoneRegister(@RequestBody UserDto userDto){
        try {
            userService.phoneRegister(userDto);
            return AjaxResult.me();
        } catch (BusinessException e) {//捕获业务异常
            e.printStackTrace();
            return AjaxResult.me().setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("系统繁忙，稍后重试！！");
        }

    }


}
